import $ from 'jquery';
import store from '@/store/';

/**
 * 设置cookie
 */
const setCookie = (name, value) => {
  var Days = 7;
  var exp = new Date();
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
};

/**
 * 获取cookie
 * @param  {[type]} name [description]
 * @return {[type]}      [description]
 */
const getCookie = (name) => {
  if (document.cookie.length > 0) {
    let start = document.cookie.indexOf(name + '=');
    if (start !== -1) {
      start = start + name.length + 1;
      let end = document.cookie.indexOf(';', start);
      if (end === -1) {
        end = document.cookie.length;
      }
      return unescape(document.cookie.substring(start, end));
    }
  }
  return '';
};

/**
 * 存储localStorage/sessionStorage
 */
const setStore = (name, content, deep) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  if (deep) {
    window.localStorage.setItem(name, content);
  } else {
    window.sessionStorage.setItem(name, content);
  }
};

/**
 * 获取localStorage/sessionStorage
 */
const getStore = (name, deep) => {
  if (!name) return;
  if (deep) {
    return window.localStorage.getItem(name);
  } else {
    return window.sessionStorage.getItem(name);
  }
};

/**
 * 删除localStorage/sessionStorage
 */
const removeStore = (name, deep) => {
  if (!name) return;
  if (deep) {
    window.localStorage.removeItem(name);
  } else {
    window.sessionStorage.removeItem(name);
  }
};

/**
 * 格式化日期
 * @param  {[type]} fmt [description]
 * @return {[type]}     [description]
 */
const DateFormat = (str, fmt) => {
  let o = {
    'M+': str.getMonth() + 1,
    'd+': str.getDate(),
    'h+': str.getHours(),
    'm+': str.getMinutes(),
    's+': str.getSeconds(),
    'q+': Math.floor((str.getMonth() + 3) / 3),
    'S': str.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (str.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    }
  }
  return fmt;
};

/**
 * 格式化日期
 * @param  {[type]} fmt [description]
 * @return {[type]}     [description]
 */
const DateFormatTZ = (dateStr) => {
  let time = (new Date(dateStr)).getTime();
  let date = DateFormat(new Date(time - 8 * 60 * 60 * 1000), 'yyyy-MM-dd hh:mm:ss');
  let dateTZ = new Date((date + '.000Z').replace(' ', 'T'));
  return dateTZ;
};

// 函数节流
const throttle = (idea, action) => {
  let last = 0;
  return function () {
    let now = +new Date();
    if (now - last > idea) {
      action && action.apply(this, arguments);
      last = now;
    }
  };
};

// 函数防抖
const debounce = (idea, action) => {
  let timer = null;
  return function () {
    let that = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(function () {
      action && action.apply(that, args);
    }, idea);
  };
};

// extend
const extend = (target, source) => {
  for (let attr in source) {
    target[attr] = source[attr];
  }
  return target;
};

// deepCopy
const deepCopy = (obj, cache = []) => {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  const hit = find(cache, c => c.original === obj);
  if (hit) {
    return hit.copy;
  }

  const copy = Array.isArray(obj)
    ? []
    : {};
  cache.push({
    original: obj,
    copy
  });

  Object.keys(obj).forEach(key => {
    copy[key] = deepCopy(obj[key], cache);
  });
  return copy;
};

/**
 * 高德地图通过上级获取下级地址信息
 * @param  {[type]} name [description]
 * @return {[type]}      [description]
 */
const amapGetRegion = (name, cb) => {
  var apiConv = 'http://restapi.amap.com/v3/config/district' +
    '?key=09fc21a01b861edccad8027462452966' +
    '&keywords=' + name +
    '&subdistrict=2' +
    '&extensions=base';
  $.getJSON(apiConv, function (data) {
    cb(data);
  });
};

const createButton = (h, params, fn, text, props, style) => {
  let defProps = props || {
    type: 'text',
    size: 'small'
  };
  let defStyle = style || {
    marginRight: '5px',
    color: '#47bac2'
  };
  return h('Button', {
    props: defProps,
    style: defStyle,
    on: {
      click: () => {
        fn(params.row);
      }
    }
  }, text);
};
/**
 * 判断字符串是否是JSON
 * @param str
 * @returns {boolean}
 */
const isJSON = (str) => {
  if (typeof str === 'string') {
    try {
      JSON.parse(str);
      if (str.indexOf('{') > -1) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
  return false;
};
const checkVIN = (sVIN) => {
  let Arr = [];
  let Brr = [];
  Arr['A'] = 1;
  Arr['B'] = 2;
  Arr['C'] = 3;
  Arr['D'] = 4;
  Arr['E'] = 5;
  Arr['F'] = 6;
  Arr['G'] = 7;
  Arr['H'] = 8;
  Arr['J'] = 1;
  Arr['K'] = 2;
  Arr['L'] = 3;
  Arr['M'] = 4;
  Arr['N'] = 5;
  Arr['P'] = 7;
  Arr['R'] = 9;
  Arr['S'] = 2;
  Arr['T'] = 3;
  Arr['U'] = 4;
  Arr['V'] = 5;
  Arr['W'] = 6;
  Arr['X'] = 7;
  Arr['Y'] = 8;
  Arr['Z'] = 9;
  Arr['1'] = 1;
  Arr['2'] = 2;
  Arr['3'] = 3;
  Arr['4'] = 4;
  Arr['5'] = 5;
  Arr['6'] = 6;
  Arr['7'] = 7;
  Arr['8'] = 8;
  Arr['9'] = 9;
  Arr['0'] = 0;
  Brr[1] = 8;
  Brr[2] = 7;
  Brr[3] = 6;
  Brr[4] = 5;
  Brr[5] = 4;
  Brr[6] = 3;
  Brr[7] = 2;
  Brr[8] = 10;
  Brr[9] = 0;
  Brr[10] = 9;
  Brr[11] = 8;
  Brr[12] = 7;
  Brr[13] = 6;
  Brr[14] = 5;
  Brr[15] = 4;
  Brr[16] = 3;
  Brr[17] = 2;
  // 车辆VIN码验证代码 上线前放开
  // var sKYZF = 'ABCDEFGHJKLMNPRSTUVWXYZ1234567890';
  // var sJYW = '';
  var bl = false;
  // var blKYZF = false;
  if (sVIN.length === 17) {
    return true; // 上线时 这里删掉
    // let iJQS = 0;
    // let intTemp = 0;
    // let ht = Arr;
    // let htZM = Brr;
    // try {
    //   for (var i = 0; i < sVIN.length; i++) {
    //     if (sKYZF.indexOf(sVIN.substr(i, 1)) !== -1) {
    //       blKYZF = true;
    //       iJQS = iJQS + parseInt(ht[sVIN.substr(i, 1)]) * parseInt(htZM[(i + 1)]);
    //     } else {
    //       blKYZF = false;
    //       break;
    //     }
    //   }
    //   if (blKYZF) {
    //     intTemp = iJQS % 11;
    //     if (intTemp === 10) {
    //       sJYW = 'X';
    //     } else {
    //       sJYW = intTemp.toString();
    //     }
    //     if (sJYW === sVIN.substr(8, 1)) bl = true;
    //   } else {
    //     bl = false;
    //   }
    // } catch (err) {
    //   bl = false;
    // }
  }
  return bl;
};
// const createSelectData = async (dataFun, keys, params, payload) => {
//   try {
//     let param = params || {page: 1, limit: 10000};
//     let res = await dataFun(param, payload);
//     if (res.data && res.data.length) {
//       let array = [];
//       array = res.data.filter(item => {
//         if (!item) return false;
//         return true;
//       }).map(item => {
//         return {value: item[keys[0]], label: item[keys[1]]};
//       });
//       return array;
//     } else if (res.data.list && res.data.list.length) {
//       let array = [];
//       array = res.data.list.filter(item => {
//         if (!item) return false;
//         return true;
//       }).map(item => {
//         return {value: item[keys[0]], label: item[keys[1]]};
//       });
//       return array;
//     } else {
//       return [];
//     }
//   } catch (e) {
//     console.log(e);
//     return [];
//   }
// };
/**
 * 改变表格加载状态
 * @param boolean
 */
const csl = (boolean) => {
  store.commit('searchLoading', boolean);
};
/**
 * 改变操作按钮加载状态
 * @param boolean
 */
const cal = (boolean) => {
  store.commit('actionLoading', boolean);
};

const createSelectData = (array, keys) => {
  if (!array) return [];
  return array.map(item => {
    return {value: item[keys[0]], label: item[keys[1]]};
  });
};
const createIconBtn = (h, params, fn, text, iconType, iconSize, style, code) => {
  let defProps = {
    text: text,
    iconType: iconType,
    iconSize: iconSize && iconSize.toString() || '20',
    authCode: code
  };
  return h('hyIconBtn', {
    props: defProps,
    style: style || {},
    on: {
      click: () => {
        fn && fn(params.row);
      }
    }
  });
};
const createMapLable = (positionInfo, carInfo) => {
  let info =
    '<div id="truckInfowin" style="background: rgba(0,0,0,.8);border-radius: 3px;box-shadow: 1px -1px 5px rgba(0,0,0,.5);padding: 10px;color: #ffffff;width: 220px;font-size: 12px;-webkit-user-select: text;-moz-user-select: text; -ms-user-select: text;">' +
    '<table>' +
    '<tbody>' +
    '<tr><th style="width: 65px; text-align: right">车牌号：</th><td>' + carInfo.no + '</td></tr>' +
    '<tr><th style="width: 65px; text-align: right">设备号：</th><td>41062636</td></tr>' +
    '<tr><th style="width: 65px; text-align: right">司机：</th> <td>彭小兵(主驾) <br> 18602317255</td> </tr> ' +
    '<tr><th style="width: 65px; text-align: right">定位时间：</th> <td>02-07 19:12:11</td> </tr> ' +
    '<tr><th style="width: 65px; text-align: right">速度：</th> <td>' + positionInfo.speed + 'KM/H</td></tr>' +
    '<tr><th style="width: 65px; text-align: right">温度：</th> <td>-:</td> </tr> ' +
    '<tr><th style="width: 65px; text-align: right">地址：</th><td class="cell-address word-break">' + positionInfo.lng + ',' + positionInfo.lat + '</td></tr>' +
    '</tbody>' +
    '</table>' +
    '<span style="position: absolute;bottom: -4px;color: rgba(0,0,0,.8);left: 50%; margin: 0 0 0 -4px;    display: inline-block;width: 0;height: 0;margin-left: 2px;vertical-align: middle;border-top: 4px dashed;border-top: 4px solid\\9; border-right: 4px solid transparent;border-left: 4px solid transparent;"></span>' +
    '<button type="button" id="closeLabel" style="position: absolute;right: 5px;top: 0;font-size: 20px;opacity: .8;color: #ffffff;font-weight: normal;-webkit-appearance: none;padding: 0;cursor: pointer;background: 0 0;border: 0;" aria-label="Close"><span aria-hidden="true">×</span></button>' +
    '</div>';
  return info;
};
// 抛出
export default {
  setCookie,
  getCookie,
  setStore,
  getStore,
  removeStore,
  DateFormat,
  DateFormatTZ,
  throttle,
  debounce,
  extend,
  deepCopy,
  amapGetRegion,
  createButton,
  isJSON,
  checkVIN,
  createSelectData,
  csl,
  cal,
  createIconBtn,
  createMapLable
};
